package com.sadam.ui4.FragmentPlusPage;

import android.Manifest;
import com.sadam.ui4.Data.Video;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import com.sadam.ui4.ActivityLogin;
import com.sadam.ui4.Data.MySqLiteOpenHelper;
import com.sadam.ui4.Data.User;
import com.sadam.ui4.MainActivity;
import com.sadam.ui4.R;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;

public class FragmentPlusPage extends Fragment {
    public static final String SHARED_PREFERENCES_KEY_VIDEO_FILE_PATH = "VIDEO_FILE_PATH_SHARED_PREFERENCES";
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // 从ActivityPublish迁移的变量
    private static final int REQUEST_VIDEO_PERMISSION = 100;
    private static final int REQUEST_PICK_VIDEO = 200;
    private static final int REQUEST_PERMISSION_SETTINGS = 300;
    private Uri selectedVideoUri;
    private ImageView ivAddContent;
    private Button btnPublish;
    private static final String TAG = "FragmentPlusPage";

    // 新增：缓存UI组件，用于后续重置
    private EditText etTitle;
    private EditText etDescription;
    private EditText etTags;

    private String mParam1;
    private String mParam2;
    private OnFragmentInteractionListener mListener;

    public FragmentPlusPage() {}

    public static FragmentPlusPage newInstance(String param1, String param2) {
        FragmentPlusPage fragment = new FragmentPlusPage();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // 加载发布页面布局
        View view = inflater.inflate(R.layout.activity_publish, container, false);

        // 初始化UI组件（新增：缓存标题、描述、标签输入框）
        ivAddContent = view.findViewById(R.id.iv_add_content);
        btnPublish = view.findViewById(R.id.btn_publish);
        etTitle = view.findViewById(R.id.et_title);
        etDescription = view.findViewById(R.id.et_description);
        etTags = view.findViewById(R.id.et_tags);

        // 选择视频按钮点击事件
        ivAddContent.setOnClickListener(v -> {
            requestStoragePermission();
        });

        // 修正：发布按钮点击事件（添加全量校验逻辑）
        btnPublish.setOnClickListener(v -> {
            // 1. 全量校验：视频、标题、描述、标签
            if (!checkPublishConditions()) {
                return; // 校验不通过，终止发布
            }

            // 2. 校验是否已登录
            User currentUser = getCurrentLoginUser();
            if (currentUser == null) {
                Toast.makeText(getContext(), "请先登录再发布视频", Toast.LENGTH_SHORT).show();
                Intent loginIntent = new Intent(getContext(), ActivityLogin.class);
                loginIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(loginIntent);
                return;
            }

            // 3. 显示“发布中”提示
            Toast.makeText(getContext(), "发布中...", Toast.LENGTH_SHORT).show();

            // 4. 执行发布逻辑（传入校验后的内容）
            String videoTitle = etTitle.getText().toString().trim();
            String videoIntro = etDescription.getText().toString().trim();
            String videoTag = etTags.getText().toString().trim();
            // 处理标签默认值（校验时已确保非空，此处仅补#）
            if (!videoTag.startsWith("#")) {
                videoTag = "#" + videoTag;
            }

            String finalVideoTag = videoTag;
            new Thread(() -> {
                boolean success = saveVideoToPathInBackground(selectedVideoUri, videoTitle, videoIntro, finalVideoTag);
                // 主线程处理结果（包含重置和跳转）
                requireActivity().runOnUiThread(() -> handlePublishResult(success));
            }).start();
        });

        // 返回按钮点击事件
        view.findViewById(R.id.iv_back).setOnClickListener(v -> {
            if (getActivity() != null) {
                getActivity().onBackPressed();
            }
        });

        return view;
    }

    /**
     * 新增：全量校验发布条件（视频、标题、描述、标签）
     * @return true=满足条件，false=不满足
     */
    private boolean checkPublishConditions() {
        // 1. 校验视频是否选择
        if (selectedVideoUri == null) {
            Toast.makeText(getContext(), "请先选择要发布的视频", Toast.LENGTH_SHORT).show();
            return false;
        }

        // 2. 校验标题是否填写（非空且非空格）
        String title = etTitle.getText().toString().trim();
        if (title.isEmpty()) {
            Toast.makeText(getContext(), "请填写视频标题", Toast.LENGTH_SHORT).show();
            etTitle.requestFocus(); // 聚焦到标题输入框，提升体验
            return false;
        }

        // 3. 校验描述是否填写（非空且非空格）
        String description = etDescription.getText().toString().trim();
        if (description.isEmpty()) {
            Toast.makeText(getContext(), "请填写作品描述", Toast.LENGTH_SHORT).show();
            etDescription.requestFocus(); // 聚焦到描述输入框
            return false;
        }

        // 4. 校验标签是否填写（非空且非空格，已限制20字）
        String tags = etTags.getText().toString().trim();
        if (tags.isEmpty()) {
            Toast.makeText(getContext(), "请填写标签（多个用逗号分隔）", Toast.LENGTH_SHORT).show();
            etTags.requestFocus(); // 聚焦到标签输入框
            return false;
        }

        // 所有条件满足
        return true;
    }

    /**
     * 统一处理发布结果：成功则重置+跳转，失败则提示
     * @param isSuccess 发布是否成功
     */
    private void handlePublishResult(boolean isSuccess) {
        if (isSuccess) {
            Toast.makeText(getContext(), "发布成功！", Toast.LENGTH_SHORT).show();
            // 获取数据库帮助类
            MainActivity mainActivity = (MainActivity) getActivity();
            MySqLiteOpenHelper dbHelper = mainActivity.getMySqLiteOpenHelper();

            // 【新增】打印 Video 表的所有数据用于调试
            try {
                ArrayList<Video> videos = dbHelper.getAllVideos();
                Log.d("FragmentPlusPage", "=== 当前 Video 表共有 " + videos.size() + " 条记录 ===");
                for (int i = 0; i < videos.size(); i++) {
                    Video video = videos.get(i);
                    Log.d(TAG, "视频 #" + i + ": ID=" + video.getId() +
                            ", 标题='" + video.getTitle() +
                            "', 用户名='" + video.getUserName() +
                            "', 路径='" + video.getUrl() +
                            "', 标签='" + video.getLabel() +
                            "', 点赞数=" + video.getLikeCount() +
                            ", 评论数=" + video.getCommentCount() + "'");
                }
            } catch (Exception e) {
                Log.e(TAG, "读取 Video 表失败", e);
            }
            // 延迟跳转：确保提示显示完整，同时执行重置
            new Handler(Looper.getMainLooper()).postDelayed(() -> {
                // 1. 重置发布界面为初始状态
                resetPublishPage();

                // 2. 跳转到首页
                if (getActivity() instanceof MainActivity) {
                    ((MainActivity) getActivity()).switchToHomePage();
                }
            }, 2000);
        } else {
            Toast.makeText(
                    getContext(),
                    "发布失败，请检查存储权限或视频格式后重试",
                    Toast.LENGTH_LONG
            ).show();
        }
    }

    /**
     * 新增：重置发布界面为初始状态（无视频、无输入内容）
     */
    private void resetPublishPage() {
        // 1. 重置视频相关（清空Uri、恢复初始图标）
        selectedVideoUri = null;
        if (ivAddContent != null) {
            ivAddContent.setImageResource(R.drawable.plus);
        }

        // 2. 重置输入框（清空内容、清除焦点）
        if (etTitle != null) {
            etTitle.setText("");
            etTitle.clearFocus();
        }
        if (etDescription != null) {
            etDescription.setText("");
            etDescription.clearFocus();
        }
        if (etTags != null) {
            etTags.setText("");
            etTags.clearFocus();
        }

        // 3. 隐藏软键盘（可选，提升体验）
        if (getActivity() != null) {
            View currentFocus = getActivity().getCurrentFocus();
            if (currentFocus != null) {
                currentFocus.clearFocus();
            }
        }
    }

    /**
     * 修改：接收校验后的标题、描述、标签，直接存入数据库
     */
    private boolean saveVideoToPathInBackground(Uri videoUri, String videoTitle, String videoIntro, String videoTag) {
        try {
            Log.d(TAG, "开始保存视频，Uri: " + videoUri);

            // 1. 获取当前登录用户
            User currentUser = getCurrentLoginUser();
            if (currentUser == null) {
                Log.e(TAG, "发布失败：未获取到有效登录用户");
                return false;
            }
            long userId = currentUser.getId();
            String username = currentUser.getName().trim();

            // 2. 获取数据库实例
            MainActivity mainActivity = (MainActivity) getActivity();
            MySqLiteOpenHelper dbHelper = mainActivity.getMySqLiteOpenHelper();
            if (dbHelper == null) {
                Log.e(TAG, "发布失败：数据库帮助类为空");
                return false;
            }

            // 3. 保存视频到内部存储
            File targetDir = new File(requireContext().getFilesDir(), "videos");
            if (!targetDir.exists() && !targetDir.mkdirs()) {
                Log.e(TAG, "无法创建目录：" + targetDir.getAbsolutePath());
                return false;
            }
            String fileName = username + "_" + System.currentTimeMillis() + ".mp4";
            File targetFile = new File(targetDir, fileName);

            // 4. 复制视频文件
            try (InputStream is = requireContext().getContentResolver().openInputStream(videoUri);
                 OutputStream os = new FileOutputStream(targetFile)) {
                if (is == null) {
                    Log.e(TAG, "无法打开视频输入流，Uri无效");
                    return false;
                }
                byte[] buffer = new byte[8192];
                int len;
                while ((len = is.read(buffer)) > 0) {
                    os.write(buffer, 0, len);
                }
            }

            // 5. 校验视频文件（确保保存成功）
            if (!targetFile.exists() || targetFile.length() < 1024) {
                Log.e(TAG, "视频保存失败，文件为空或不存在，路径：" + targetFile.getAbsolutePath());
                return false;
            }
            Log.d(TAG, "视频保存成功，路径：" + targetFile.getAbsolutePath() + "，大小：" + targetFile.length() + "字节");

            // 6. 校验Video表并插入数据（使用校验后的内容）
            if (!checkVideoTableExists(dbHelper)) {
                Log.e(TAG, "数据库中不存在Video表");
                targetFile.delete();
                return false;
            }
            Long videoId = dbHelper.insertVideo(userId, targetFile.getAbsolutePath(), videoTitle, videoIntro, videoTag);
            if (videoId == null || videoId == -1) {
                Log.e(TAG, "数据库插入视频失败，insertVideo返回ID：" + videoId);
                targetFile.delete();
                return false;
            }
            Log.d(TAG, "视频插入数据库成功，视频ID：" + videoId + "，所属用户ID：" + userId);
            return true;

        } catch (Exception e) {
            Log.e(TAG, "发布失败（未知异常）：" + e.getMessage(), e);
            return false;
        }
    }

    // 修正：返回long类型，复用dbHelper，避免重复创建
    private long getUserIdByUsername(String username, MySqLiteOpenHelper dbHelper) {
        if (dbHelper == null || username == null || username.isEmpty()) {
            Log.e(TAG, "getUserIdByUsername参数无效，dbHelper：" + (dbHelper != null) + "，username：" + username);
            return -1;
        }
        // 使用dbHelper的可读数据库，避免新建连接
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        if (db == null || !db.isOpen()) {
            Log.e(TAG, "获取可读数据库失败或数据库未打开");
            return -1;
        }

        long userId = -1;
        Cursor cursor = null;
        try {
            // 查询User表，只查未删除的用户（isDeleted=0）
            cursor = db.query(
                    "User",                // 表名
                    new String[]{"id"},    // 查询字段（只查id）
                    "name = ? AND isDeleted = 0", // 条件：用户名匹配且未删除
                    new String[]{username}, // 条件参数
                    null, null, null, "1"  // 限制只返回1条结果
            );
            if (cursor != null && cursor.moveToFirst()) {
                // 用getColumnIndexOrThrow避免列名错误，返回long类型
                int idColumnIndex = cursor.getColumnIndexOrThrow("id");
                userId = cursor.getLong(idColumnIndex);
                Log.d(TAG, "查询到用户ID，username：" + username + "，userId：" + userId);
            } else {
                Log.e(TAG, "未查询到用户，username：" + username + "，cursor是否为空：" + (cursor == null));
            }
        } catch (SQLiteException e) {
            Log.e(TAG, "查询用户ID失败（SQLiteException）：" + e.getMessage(), e);
        } finally {
            // 关闭游标，避免内存泄漏
            if (cursor != null) cursor.close();
            // 不关闭db，由dbHelper统一管理
        }
        return userId;
    }

    // 新增：校验Video表是否存在（在插入前调用）
    private boolean checkVideoTableExists(MySqLiteOpenHelper dbHelper) {
        if (dbHelper == null) return false;
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        if (db == null) return false;

        Cursor cursor = null;
        try {
            // 查询SQLite系统表，判断Video表是否存在
            cursor = db.rawQuery(
                    "SELECT name FROM sqlite_master WHERE type='table' AND name=?",
                    new String[]{"Video"}
            );
            return cursor != null && cursor.moveToFirst();
        } catch (Exception e) {
            Log.e(TAG, "校验Video表存在性失败：" + e.getMessage(), e);
            return false;
        } finally {
            if (cursor != null) cursor.close();
        }
    }

    /**
     * 辅助方法：判断存储权限是否已授予（兼容Android 13+）
     * @return true=已授予，false=未授予
     */
    private boolean isStoragePermissionGranted() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { // Android 13+
            return ContextCompat.checkSelfPermission(requireContext(),
                    Manifest.permission.READ_MEDIA_VIDEO) == PackageManager.PERMISSION_GRANTED;
        } else { // Android 12 及以下
            int readGranted = ContextCompat.checkSelfPermission(requireContext(),
                    Manifest.permission.READ_EXTERNAL_STORAGE);
            return readGranted == PackageManager.PERMISSION_GRANTED;
        }
    }

    /**
     * 优化：存储权限请求逻辑（区分首次请求/用户已拒绝场景）
     */
    private void requestStoragePermission() {
        if (isStoragePermissionGranted()) {
            pickVideoFromGallery();
            return;
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            // Android 13+ 请求 READ_MEDIA_VIDEO
            ActivityCompat.requestPermissions(
                    requireActivity(),
                    new String[]{Manifest.permission.READ_MEDIA_VIDEO},
                    REQUEST_VIDEO_PERMISSION
            );
        } else {
            // Android 12 及以下请求 READ_EXTERNAL_STORAGE
            String[] perms = {Manifest.permission.READ_EXTERNAL_STORAGE};
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                perms = new String[]{
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                };
            }
            ActivityCompat.requestPermissions(requireActivity(), perms, REQUEST_VIDEO_PERMISSION);
        }
    }

    /**
     * 跳转系统应用设置页，让用户手动开启存储权限
     */
    private void openPermissionSettings() {
        try {
            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            Uri uri = Uri.fromParts("package", requireContext().getPackageName(), null);
            intent.setData(uri);
            // 使用新的 launcher 启动
            permissionSettingsLauncher.launch(intent);
        } catch (Exception e) {
            Log.e(TAG, "跳转权限设置页失败", e);
            Toast.makeText(getContext(), "跳转设置页失败，请手动到“设置-应用-UI4-权限”开启存储权限", Toast.LENGTH_LONG).show();
        }
    }

    private final ActivityResultLauncher<Intent> permissionSettingsLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            result -> {
                // 从设置页返回后，重新检查权限
                if (isStoragePermissionGranted()) {
                    Toast.makeText(getContext(), "存储权限已开启，可选择视频", Toast.LENGTH_SHORT).show();
                    pickVideoFromGallery();
                } else {
                    Toast.makeText(getContext(), "未开启存储权限，无法选择视频", Toast.LENGTH_SHORT).show();
                }
            }
    );

    /**
     * 优化：权限请求结果处理（明确提示用户后续操作）
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode != REQUEST_VIDEO_PERMISSION) return;

        boolean granted = true;
        for (int result : grantResults) {
            if (result != PackageManager.PERMISSION_GRANTED) {
                granted = false;
                break;
            }
        }

        if (granted) {
            Toast.makeText(getContext(), "权限已授予", Toast.LENGTH_SHORT).show();
            pickVideoFromGallery();
        } else {
            Toast.makeText(getContext(), "需要权限才能选择视频，请手动开启", Toast.LENGTH_LONG).show();
            openPermissionSettings();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // 场景1：从权限设置页返回，重新检查权限
        if (requestCode == REQUEST_PERMISSION_SETTINGS) {
            if (isStoragePermissionGranted()) {
                Toast.makeText(getContext(), "存储权限已开启，可选择视频", Toast.LENGTH_SHORT).show();
                pickVideoFromGallery();
            } else {
                Toast.makeText(getContext(), "未开启存储权限，无法选择视频", Toast.LENGTH_SHORT).show();
            }
        }
        // 场景2：从相册选择视频返回（原有逻辑保留）
        else if (requestCode == REQUEST_PICK_VIDEO && resultCode == getActivity().RESULT_OK && data != null) {
            selectedVideoUri = data.getData();
            if (selectedVideoUri == null) {
                Toast.makeText(getContext(), "视频路径获取失败", Toast.LENGTH_SHORT).show();
                return;
            }

            Log.d(TAG, "选中的视频Uri: " + selectedVideoUri.toString());
            Toast.makeText(getContext(), "已选择视频", Toast.LENGTH_SHORT).show();

            // 生成缩略图（原有逻辑保留）
            Bitmap thumbnail = getVideoThumbnail(selectedVideoUri);
            if (thumbnail != null) {
                int targetWidth = ivAddContent.getWidth() > 0 ? ivAddContent.getWidth() : 100;
                int targetHeight = ivAddContent.getHeight() > 0 ? ivAddContent.getHeight() : 100;
                Bitmap scaledThumbnail = Bitmap.createScaledBitmap(thumbnail, targetWidth, targetHeight, true);
                ivAddContent.setImageBitmap(scaledThumbnail);
                thumbnail.recycle();
            } else {
                Toast.makeText(getContext(), "缩略图生成失败", Toast.LENGTH_SHORT).show();
                ivAddContent.setImageResource(R.drawable.plus);
            }
        }
    }

    // 三种方法获取视频缩略图
    private Bitmap getVideoThumbnail(Uri videoUri) {
        // 方法1: 使用MediaMetadataRetriever
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
            retriever.setDataSource(requireContext(), videoUri);
            Bitmap bitmap = retriever.getFrameAtTime(1000000);
            if (bitmap != null) {
                Log.d(TAG, "使用MediaMetadataRetriever获取缩略图成功");
                return bitmap;
            }
        } catch (Exception e) {
            Log.e(TAG, "MediaMetadataRetriever方法失败: " + e.getMessage());
        } finally {
            try {
                retriever.release();
            } catch (IOException e) {
                Log.e(TAG, "释放MediaMetadataRetriever失败: " + e.getMessage());
            }
        }

        // 方法2: 使用MediaStore系统缩略图
        try {
            String[] projection = {MediaStore.Video.Media._ID};
            Cursor cursor = requireContext().getContentResolver().query(videoUri, projection, null, null, null);
            if (cursor != null && cursor.moveToFirst()) {
                int idColumnIndex = cursor.getColumnIndex(MediaStore.Video.Media._ID);
                long videoId = cursor.getLong(idColumnIndex);
                cursor.close();

                Bitmap bitmap = MediaStore.Video.Thumbnails.getThumbnail(
                        requireContext().getContentResolver(),
                        videoId,
                        MediaStore.Video.Thumbnails.MINI_KIND,
                        null
                );
                if (bitmap != null) {
                    Log.d(TAG, "使用MediaStore获取缩略图成功");
                    return bitmap;
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "MediaStore方法失败: " + e.getMessage());
        }

        // 方法3: 使用文件路径生成缩略图
        try {
            String filePath = getRealPathFromUri(videoUri);
            if (filePath != null) {
                Bitmap bitmap = ThumbnailUtils.createVideoThumbnail(
                        filePath,
                        MediaStore.Video.Thumbnails.MINI_KIND
                );
                if (bitmap != null) {
                    Log.d(TAG, "使用文件路径获取缩略图成功");
                    return bitmap;
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "文件路径方法失败: " + e.getMessage());
        }

        return null;
    }

    // 将Uri转换为真实文件路径
    private String getRealPathFromUri(Uri uri) {
        if (uri == null) return null;

        String path = uri.getPath();
        if (path != null && new File(path).exists()) {
            return path;
        }

        String[] projection = {MediaStore.Video.Media.DATA};
        try (Cursor cursor = requireContext().getContentResolver().query(uri, projection, null, null, null)) {
            if (cursor != null && cursor.moveToFirst()) {
                int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
                return cursor.getString(columnIndex);
            }
        } catch (Exception e) {
            Log.e(TAG, "获取真实路径失败: " + e.getMessage());
        }
        return null;
    }

    // 打开相册选择视频
    private void pickVideoFromGallery() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
        intent.setType("video/*");
        if (intent.resolveActivity(requireContext().getPackageManager()) != null) {
            startActivityForResult(intent, REQUEST_PICK_VIDEO);
        } else {
            Toast.makeText(getContext(), "未找到可处理视频选择的应用", Toast.LENGTH_SHORT).show();
        }
    }

    // 从SharedPreferences获取当前登录用户（完全复用ActivityLogin的逻辑）
    private User getCurrentLoginUser() {
        // 1. 从MainActivity获取数据库帮助类（避免重复创建）
        MainActivity mainActivity = (MainActivity) getActivity();
        if (mainActivity == null || mainActivity.getMySqLiteOpenHelper() == null) {
            Log.e(TAG, "获取当前用户失败：MainActivity或数据库实例为空");
            return null;
        }
        MySqLiteOpenHelper dbHelper = mainActivity.getMySqLiteOpenHelper();

        // 2. 调用ActivityLogin的静态方法，读取登录用户（路径和键名完全一致）
        User currentUser = ActivityLogin.getCurrentUserFromSharedPrefrences(requireContext(), dbHelper);
        if (currentUser == null || currentUser.getName() == null || currentUser.getId() == 0) {
            Log.e(TAG, "未获取到有效登录用户，User对象为空或ID/用户名为空");
            Log.d(TAG, "调试：currentUser=" + (currentUser != null ? currentUser.getName() : "null"));
            return null;
        }

        // 3. 校验用户是否存在于数据库（避免SP存储的用户已被删除）
        User dbUser = dbHelper.getUserByName(currentUser.getName().trim());
        if (dbUser == null) {
            Log.e(TAG, "SP中存储的用户不存在于数据库，用户名：" + currentUser.getName());
            // 清除无效的登录状态（调用ActivityLogin的SP路径）
            SharedPreferences sp = requireContext().getSharedPreferences(
                    ActivityLogin.SHARED_PREFRENCES_CURRENT_USER, Context.MODE_PRIVATE
            );
            sp.edit().clear().apply();
            return null;
        }

        Log.d(TAG, "获取到有效登录用户：用户名=" + dbUser.getName() + "，用户ID=" + dbUser.getId());
        return dbUser;
    }

    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    public interface OnFragmentInteractionListener {
        void onFragmentInteraction(Uri uri);
    }
}